import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from "@/views/Index"

Vue.use(VueRouter)

const routes = [
    {
        path: '/', // 首页
        name: 'Layout',
        component: Index,
        redirect: "/home",
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import("@/views/Home"),
            },
        ]
    },
    {
        path: '/login', // 登录
        name: 'Login',
        component: () => import("@/views/Login")
    },
]

const router = new VueRouter({
    mode: "hash",
    // base: process.env.BASE_URL,  // 如果使用history模式，必须设置base参数
    routes
})

// 在刷新页面的时候重置当前路由
activeRouter()

function activeRouter() {
    const menusStr = sessionStorage.getItem("manage-menus");
    if (menusStr) {
        const menus = JSON.parse(menusStr)
        let root = {
            path: '/',
            name: 'Layout',
            component: Index,
            redirect: "/home",
            children: []
        }
        menus.forEach(p => {
            renderRouter(root, p)
        })
        if (router) {
            router.addRoute(root)
        }
    }
}

function renderRouter(root, parent) {
    if (parent.children.length > 0) {
        parent.children.forEach(child => {
            renderRouter(root, child)
        })
    } else {
        let obj = {
            path: parent.path.startsWith('/') ? parent.path : '/' + parent.path,
            name: parent.name,
            component: () => import("@/views/" + parent.pagePath + ".vue")
        };
        root.children.push(obj)
    }
}

router.beforeEach((to, from, next) => {

    if (to.path === '/login' || to.path === '/register') {
        next()
        return
    }
    if (!sessionStorage.getItem("manage-token")) {
        next('/login')
        return;
    }

    let menus = sessionStorage.getItem("manage-menus") ? JSON.parse(sessionStorage.getItem("manage-menus")) : {}
    if (!menus || !menus.length) {
        next('/login')
    }
        // else if (!menus.find(p => p.path === to.path)) {
        //   next('/login')
    // }
    else {
        next()
    }
})

//添加以下代码
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router
